<template>
  <div class="table">
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-delete" style="margin-right:10px" @click="handleCloseAll">批量封号</el-button>
        <el-input v-model="listQuery.username" placeholder="用户名" style="width:90px" />
        <el-input v-model="listQuery.sellername" placeholder="店铺名" style="width:180px" />
        <el-input v-model="listQuery.phone" placeholder="电话" style="width:180px" />

        <el-input v-model="listQuery.address" placeholder="地址" style="width:200px" />
        <el-button type="primary" icon="el-icon-search" :disabled="isDisable" @click="search">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" :disabled="isDisable" @click="handleCreate">添加</el-button>
      </div>
      <div class="table">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          element-loading-text="拼命加载中"
          border
          fit
          highlight-current-row
          style="width: 100%"
          :row-style="{height:'0px'}"
          :cell-style="{padding:'0px'}"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="45"
            align="center"
          />
          <el-table-column
            prop="username"
            label="用户名"
          />
          <el-table-column
            prop="sellername"
            label="店铺名"
          />
          <el-table-column
            prop="phone"
            label="联系电话"
          />
          <el-table-column
            prop="address"
            label="地址"
          />
          <el-table-column label="店铺logo" width="100px" height="100px" aligin="center">
            <template slot-scope="scope">
              <el-card :body-style="{ padding: '0px' }">
                <img :src="scope.row.logo?scope.row.logo:''" class="image" :onerror="defaultAvatar">
              </el-card>
            </template>
          </el-table-column>
          <el-table-column label="分数" align="center" width="170px">
            <template slot-scope="scope">
              <el-rate
                v-model="scope.row.star"
                :colors="colors"
                show-score
                text-color="#ff9900"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200px">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-close" class="warnning" @click="close(scope.row)">封号</el-button>
              <el-button type="text" icon="el-icon-delete" class="red" @click="goToDelGoods(scope.row)">查封菜品</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            v-if="total"
            background
            :current-page="listQuery.pn"
            :page-sizes="[5,10, 20, 25, 30]"
            :page-size="listQuery.ps"
            layout="total, slot, sizes, prev, pager, next, jumper"
            :total="totalNumber"
            @current-change="pageChange"
            @size-change="sizeChange"
          />
        </div>
      </div>

      <!-- 查封提示框 -->
      <el-dialog title="提示" :visible.sync="closeVisible" width="300px" center>
        <div class="del-dialog-cnt">查封不可恢复，是否确定查封？</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelClose">取 消</el-button>
          <el-button type="primary" @click="closeRow">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 批量删除提示框 -->
      <el-dialog title="提示" :visible.sync="closeAllVisible" width="300px" center>
        <div class="del-dialog-cnt">是否确定批量查封？</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelClose">取 消</el-button>
          <el-button type="primary" @click="confirmCloseAll">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 批量删除第二次提示框 -->
      <el-dialog title="提示" :visible.sync="confirmCloseAllVisible" width="320px" center>
        <div class="del-dialog-cnt">批量查封不可恢复，是否确定查封？</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelClose">取 消</el-button>
          <el-button type="primary" @click="closeAll">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加弹出框 -->
      <el-dialog v-loading="listLoading" title="添加" :visible.sync="addVisible" width="30%">
        <el-form ref="temp" :rules="rules" :model="temp" label-width="100px">
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="temp.username" placeholder="请输入用户名：" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input v-model="temp.password" placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="店铺名：" prop="sellername">
            <el-input v-model="temp.sellername" placeholder="请输入店铺名" />
          </el-form-item>
          <el-form-item label="联系电话：" prop="phone">
            <el-input v-model="temp.phone" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="店铺地址：" prop="address">
            <el-input v-model="temp.address" placeholder="请输入店铺地址" />
          </el-form-item>
          <el-form-item label="类型：" prop="categoryId">
            <el-select v-model="temp.categoryId" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="打包费：" prop="packCost">
            <el-input v-model="temp.packCost" placeholder="请输入打包费" />
          </el-form-item>
          <el-upload action="" :on-change="getFile" :limit="1" list-type="picture" :auto-upload="false">
            <el-button size="small" type="primary">选择店铺图片上传,最多上传一张图片</el-button>
          </el-upload>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAdd()">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getSellersList, closeSellers, AddSeller, GetAllSellerCategory } from '@/api/users/seller'
import qs from 'qs'
export default {
  name: 'Basetable',
  data() {
    var isPrice = (rule, value, callback) => {
      var pattern = /^\d+(\.\d{1,2})?$/
      if (!pattern.test(value)) {
        callback(new Error('请输入正确金额，小数点后最多两位，如5.55'))
      } else {
        callback()
      }
    }
    return {
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
      multipleSelection: [],
      closeAllVisible: false, // 是否弹出批量删除确认框
      confirmCloseAllVisible: false,
      isDisable: false, // 是否禁用搜索按钮
      closeVisible: false, // 是否弹出查封用户账号的
      addVisible: false, // 是否弹出添加商家弹框
      tableData: [],
      typeOptions: [], // 商铺类型
      listLoading: false, // 添加商家弹框的loading

      // 查询条件：
      listQuery: {
        pn: 1, // 当前页数 int
        ps: 5, // 每页大小 int
        phone: '',
        username: '',
        sellername: '',
        address: ''
        // sort: '+id'
      },
      total: undefined, // 总页数
      totalNumber: undefined, // 总条数

      // 查封参数：
      closeList: {
        list: []
      },
      // 添加参数：
      temp: {
        username: '',
        password: '',
        sellername: '',
        phone: '',
        address: '',
        categoryId: undefined,
        packCost: undefined,
        logo: undefined
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { max: 30, message: '长度30个字符以内', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { max: 20, message: '长度20个字符以内', trigger: 'blur' }
        ],
        sellername: [
          { required: true, message: '请输入店铺名', trigger: 'blur' },
          { max: 30, message: '长度30个字符以内', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '输入联系电话', trigger: 'blur' },
          { pattern: /^(1[0-9][0-9])\d{8}$/, message: '请输入正确的电话号码' }
        ],
        address: [
          { required: true, message: '请输入店铺地址', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择类型', trigger: 'blur' }
        ],
        packCost: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { validator: isPrice, trigger: 'blur' }
        ],
        logo: [
          { required: true, message: '请选择图片', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    defaultAvatar() {
      return 'this.src="' + require('../../../assets/img/elm.png') + '"'
    }
  },
  created() {
    this.listLoading = false
    this.getList()
    // console.log('checkPhone--->' + this.checkPhone('123fvsd'))
  },
  methods: {
    // 分页：
    pageChange(num) {
      this.listQuery.pn = num
      this.getList()
    },
    sizeChange(num) {
      this.listQuery.ps = num
      // this.paginationData.currentPage == 1 && this.requestListData()
      // 每一页改变当前显示条数需要重新请求数据
      this.getList()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getList() {
      this.listLoading = true
      this.tableData = []
      getSellersList(qs.stringify(this.listQuery)).then(res => {
        this.total = res.SellerList.totalPage
        this.totalNumber = res.SellerList.totalCount
        if (res.SellerList.list !== null && res.SellerList.list.length !== 0) {
          this.tableData = res.SellerList.list
          this.listLoading = false
        } else {
          this.tableData = []
          this.listLoading = false
        }
      }).catch(
        setTimeout(() => {
          this.listLoading = false
        }, 1 * 1000)
      )
    },

    search() {
      this.isDisable = true
      this.tableData = []
      this.getList()
      setTimeout(() => {
        this.isDisable = false// 点击一次时隔两秒后才能再次点击
      }, 2000)
    },
    goToDelGoods(row) {
    // 跳转到查封商品的页面，把参数商家的id传过去
      // this.$router.push({ path: '/usersManagement/delGoods' })
      this.$router.push({ path: '/usersManagement/delGoods', query: { id: row.id }})
    },
    close(row) {
      this.closeList.list.push(row.id)
      this.closeVisible = true
    },
    closeRow() {
      // 把closeList里面要查封的商品ID传给后端
      var params = new URLSearchParams()
      params.append('closeList', this.closeList.list)
      closeSellers(params).then(response => {
        if (response.code === 200) {
          this.$message.success('查封成功')
          this.closeList.list = []
          this.getList()
        } else {
          this.$message.warning('查封失败')
        }
        this.closeList.list = []
      })
      this.closeVisible = false
      this.closeAllVisible = false
      this.confirmCloseAllVisible = false
    },
    cancelClose() {
      this.closeVisible = false
      this.closeAllVisible = false
      this.confirmCloseAllVisible = false
      // 清空选项，项目中：请求接口后，重新请求数据渲染页面的时候，使用此方式，清空选中勾选状态。
      this.multipleSelection = []
    },
    handleCloseAll() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请先选择待查封的商家')
      } else {
        this.closeAllVisible = true
      }
    },
    confirmCloseAll() {
      this.closeAllVisible = false
      this.confirmCloseAllVisible = true
    },
    closeAll() {
      const length = this.multipleSelection.length
      for (let i = 0; i < length; i++) {
        this.closeList.list.push(this.multipleSelection[i].id)
      }
      this.closeRow()
      this.multipleSelection = []
    },
    getSellerCategory() {
      GetAllSellerCategory().then(response => {
        if (response.SellerCategoryList !== null) {
          this.typeOptions = response.SellerCategoryList
        } else {
          this.typeOptions = []
        }
      })
    },

    handleCreate() {
      this.resetTemp()
      this.getSellerCategory()
      this.addVisible = true
    },
    saveAdd() {
      this.listLoading = true
      this.$refs['temp'].validate((valid) => {
        if (valid) {
          this.listLoading = true
          AddSeller(qs.stringify(this.temp)).then(response => {
            if (response.code === 200) {
              this.$message.success('添加成功')
              this.getList()
            } else {
              this.$message.warning('添加失败！')
            }
          }).catch(
            setTimeout(() => {
              this.listLoading = false
              this.addVisible = false
            }, 2 * 1000)
          )
          this.listLoading = false
          this.addVisible = false
        } else {
          this.listLoading = false
          return false
        }
      })
    },
    resetTemp() {
      if (this.$refs['temp'] !== undefined) {
        this.$refs['temp'].resetFields()
      }
      this.temp = {
        username: '',
        password: '',
        sellername: '',
        phone: '',
        address: '',
        categoryId: undefined,
        packCost: undefined,
        logo: undefined
      }
    },
    /* 图像*/
    getBase64(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function() {
          imgResult = reader.result
        }
        reader.onerror = function(error) {
          reject(error)
        }
        reader.onloadend = function() {
          resolve(imgResult)
        }
      })
    },
    getFile(file, fileList) {
      var that = this
      this.getBase64(file.raw).then(res => {
        that.temp.logo = res
        // that.form.photo = res
        console.log(res)
      })
    }
  }
}
</script>
<style scoped>
  .image {
    /* height: 70px; */
    width: 100%;
    display: block;
  }
.page{
  margin-top: 1%;
  margin-bottom: 2%;
  float: right;
}
.container{
  margin-left: 30px;
  margin-right: 30px;
  margin-top: 30px;
}
    .handle-box {
        margin-bottom: 20px;
        margin-top: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 120px;
        display: inline-block;
    }
    .del-dialog-cnt{
        font-size: 16px;
        text-align: center
    }
    .table{
        width: 100%;
        font-size: 14px;
    }
    .red{
        color: #ff0000;
    }
    .warnning{
        color: #bd5a09;
    }
    .mr10{
        margin-right: 10px;
    }
</style>
